/*
    2018年5月8日 星期二
    会员，登录以及注册
*/
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createForm } from 'rc-form'
import { 
    NavBar, Icon,
    List, InputItem,
    Button, WhiteSpace,
    Radio, NoticeBar,
    Toast
} from 'antd-mobile';
const RadioItem = Radio.RadioItem

import {
    // BrowserRouter as Router, 
    HashRouter as Router, 
    Route, Link
} from 'react-router-dom'
import axios from 'axios'
import Cythina from '../cythina'
import qs from 'qs'
const Cy = new Cythina()
import VersionFooter from '../components/VersionFooter'

/**
 * 用户登录
 * @class Login
 */
class LoginForm extends React.Component{
    constructor(...args) {
        // 登录后不再重复登录
        let token = Cy.args('token')
        if(token){
            Cythina.token(token)
            Toast.success('您已经登录系统！', 3, () => {
                location.href = '/user'
            })
        }
        super(...args);
        this.state = {
          initData: '',
          show: false,
          noSubmit: false,
        };
      }
      /**
       * 保存数据
       * @memberof Login
       */
      onSubmit = () => {
        this.props.form.validateFields((err, values) => {
            // console.log(err, values)
            if(err){
                for(let key in err){
                    Toast.fail(err[key].errors[0].message) 
                    return
                }
            }else{
                this.setState({
                    noSubmit: true
                })        
                setImmediate(() => {
                    this.setState({
                        noSubmit: false
                    })   
                }, 5000)
                axios.post('/auth/login', qs.stringify(values))
                    .then((rs) => {
                        this.setState({
                            noSubmit: false
                        })   
                        let {data} = rs
                        if(data.error == 1){
                            Toast.fail(data.msg) 
                        }else{
                            Cythina.token(data.msg)
                            location.href = '/'
                        }
                    })
            }            
            // if(err){
                // console.log(typeof err, values)
                // Toast.info(err[0])
            // }
        })
      }
      render(){
        let errors
        const { getFieldProps, getFieldError } = this.props.form;
        return (
            <div>
                <NavBar
                    icon={<Icon type="left" />}
                    onLeftClick={() => location.href = '/'}
                    mode="light"
                >
                    登录系统
                </NavBar>
                <WhiteSpace />

                <List>
                    <InputItem
                        placeholder="请输入用户代码"
                        {...getFieldProps('user_code',{
                            rules: [
                              {
                                required: true,
                                message: '用户代码必填',
                              },
                            ],
                          })}
                        clear
                    >
                        用户账号</InputItem>
                    {(errors = getFieldError('required')) ? errors.join(',') : null}
                    <InputItem
                        placeholder="请输入登录密码"
                        type = "password"
                        {...getFieldProps('pswd',{
                            rules: [
                              {
                                required: true,
                                message: '登录密码不可为空！',
                              },
                            ],
                          })}
                        clear
                    >
                        登录密码</InputItem>
                </List>

                <WhiteSpace size="lg" />

                <NoticeBar 
                    mode="link"
                    // marqueeProps={{ loop: true, style: { padding: '0 7.5px' } }}
                    // onClick={() => <Redirect to="/register"/>}   // 需要远程的方法
                    onClick={() => location.href='#/register'}
                    >
                    还没有账号，赶快去注册吧！
                </NoticeBar>

                <WhiteSpace />
                <Button 
                    onClick = {this.onSubmit}
                    disabled = {this.state.noSubmit}
                    type="primary">登录</Button>
                <WhiteSpace />
                {/* <div style={{marginTop: 500}}></div> */}
                <VersionFooter 
                    // style={{marginTop: 500}}
                    />
            </div>
        )
      }
}

// 注册页面
class RegisterForm extends React.Component{
    state = {        
        account: '',
        name: '',
        gender: 'M',
        pswd: '',
        ck_pswd: '',
    };
    constructor(...args) {
        super(...args);
    }
    onGenderChange = (value) => {
        this.setState({
            gender: value
        });
    }
    onSubmit = () => {
        // let data = this.state
        // console.log(data)
        this.props.form.validateFields((err, values) => {
            console.log(err, values)
        })
    }
    render(){
        const { getFieldProps } = this.props.form;
        const { gender } = this.state;
        const genderRs = [
            { value: 'M', label: '男' },
            { value: 'F', label: '女' },
          ];
        return (            
            <div>
                <NavBar
                    icon={<Icon type="left" />}
                    onLeftClick={() => location.href = '/'}
                    mode="light"
                >
                    用户注册
                </NavBar>
                <WhiteSpace />

                <List renderHeader={() => '基本账号设置'}>
                    <InputItem
                        placeholder="包括数字、英文或下划线"
                        {...getFieldProps('account')}
                        clear
                    >
                        用户账号</InputItem>
                    <InputItem
                        placeholder="请设置登录密码"
                        type = "password"
                        {...getFieldProps('pswd')}
                        clear
                    >
                        用户密码</InputItem>
                    <InputItem
                        placeholder="输入密码确认前后一致"
                        type = "password"
                        {...getFieldProps('ck_pswd')}
                        clear
                    >
                        确认密码</InputItem>
                </List>

                <WhiteSpace />
                <List renderHeader={() => '用户信息'}>
                    <InputItem
                        {...getFieldProps('name')}
                        clear
                    >
                        姓名</InputItem>
                </List>
                <List renderHeader={() => '性别'}>
                    {genderRs.map(i => (
                    <RadioItem key={i.value} checked={gender === i.value} onChange={() => this.onGenderChange(i.value)} >
                        {i.label}
                    </RadioItem>
                    ))}
                </List>
                
                <WhiteSpace />
                <NoticeBar 
                    mode="link"
                    onClick={() => location.href='#/login'}
                    >
                    已经有账号，赶快登陆系统吧！
                </NoticeBar>

                <WhiteSpace />
                
                <Button 
                    onClick = {this.onSubmit}
                    type="primary">注册</Button>
                <WhiteSpace />
                <VersionFooter style={{MarginTop: 100}}/>
            </div>
        )
    }
}

const Login = createForm()(LoginForm)
const Register = createForm()(RegisterForm)
ReactDOM.render(
    <Router>
        <div>
            {/* <Link to="/login">登录系统</Link> */}
            {/* <Link to="/register">注册</Link> */}
            <Route path="/login" component={Login} />
            <Route path="/register" component={Register} />
        </div>
    </Router>
    , Cy.query('#container')
)

